package com.hyk.commonLib.common.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;

/**
 * Created by 贺玉琨 on 2019/3/6 0006.
 */
public class GsonUtils {
    private static Gson gson;
    private static final ArrayList<GsonParserRegister> gsonParserRegisterList = new ArrayList<>();

    public static synchronized Gson getInstance() {
        if (gson == null) {
            GsonBuilder gsonBuilder = new GsonBuilder().serializeNulls();
            for (GsonParserRegister gsonParserRegister : gsonParserRegisterList) {
                if (gsonParserRegister != null) {
                    gsonParserRegister.register(gsonBuilder);
                }
            }
//                    .registerTypeAdapter(ModelUser.class, new ModelUserDeserializer())
            gson = gsonBuilder.create();
        }
        return gson;
    }

    public static boolean validate(String json) {
        if (StringUtils.isBlank(json)) {
            return false;
        }
        try {
            JsonParser.parseString(json);
            return true;
        } catch (JsonParseException e) {
            return false;
        }
    }

    public static void addGsonParserRegister(GsonParserRegister customizer) {
        gsonParserRegisterList.add(customizer);
        gson = null;
    }

    public interface GsonParserRegister {
        void register(GsonBuilder gsonBuilder);
    }
}